<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('新增目标检测数据集')"/>
<!--    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">-->
    <link rel="stylesheet" href="/fontawesome-free-6.4.0-web/css/all.min.css">
    <script src="/sweetalert2-11.12.2/sweetalert2@11.js"></script>
    <script src="/axios/axios.min.js"></script>
    <style>
        /* 将高和宽输入框放在同一行 */
        .input-group {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .input-group .form-control {
            flex: 1; /* 输入框占据剩余空间 */
        }

        .input-group .form-control + .form-control {
            margin-left: 10px; /* 高和宽输入框之间的间距 */
        }

        /* 增加form-group的外边距 */
        .form-group {
            margin-bottom: 50px;
        }

        /* 增加label和input的字体大小 */
        .form-group label,
        .form-group input[type="file"],
        .form-group span.help-block {
            font-size: 16px; /* 或者你想要的任何值 */
        }

        #image-upload,
        #label-upload,
        #imageVal-upload,
        #labelVal-upload,
        #image-count,
        #label-count,
        #imageVal-count,
        #labelVal-count {
            /* 这里可以添加更多样式，例如字体大小、颜色等 */
            font-size: 18px; /* 示例字体大小 */
        }

        /*----------------------------------------------------------------------------------------*/
        /* 样式加载覆盖层 */
        #loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            display: none; /* 初始隐藏 */
            flex-direction: column; /* 垂直布局 */
        }

        /* 进度条容器 */
        .progress-container {
            width: 80%;
            background-color: #f3f3f3;
            border-radius: 4px;
            overflow: hidden;
            margin-top: 20px;
        }

        /* 进度条 */
        .progress-bar {
            width: 0%;
            height: 20px;
            background-color: #3498db;
            text-align: center;
            line-height: 20px; /* 水平居中 */
            color: white;
            transition: width 0.3s; /* 平滑过渡 */
        }

        #loading-overlay p {
            font-size: 30px;
        }
    </style>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-app01Dataset-add">
        <div class="form-group">
            <label class="col-sm-3 control-label">数据集名称：</label>
            <div class="col-sm-8">
                <input id="name" name="name" class="form-control" type="text">
            </div>
        </div>

        <!-- 将高和宽输入框放在同一行 -->
        <div class="form-group">
            <label class="col-sm-3 control-label">尺寸：</label>
            <div class="col-sm-8">
                <div class="input-group">
                    <input id="height" name="height" class="form-control" type="text" placeholder="高">
                    <input id="width" name="width" class="form-control" type="text" placeholder="宽">
                </div>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label">上传图片：</label>
            <div class="col-sm-8">
                <!--                只能上传jpg,jpeg,png,tif,tiff格式的图片 -->
                <input id="image-upload" type="file" accept="image/jpeg,image/png,image/jpg,image/tiff,image/tif"
                       multiple>
                <span id="image-count" class="help-block">上传的图片数量：0</span>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label">上传标签：</label>
            <div class="col-sm-8">
                <!--                 yolo只能上传txt格式的标签文件-->
                <input id="label-upload" type="file" accept=".txt" multiple>
                <span id="label-count" class="help-block">上传的标签数量：0</span>
            </div>
        </div>

        <!-- 添加是否公开的选项 -->
        <div class="form-group">
            <label class="col-sm-3 control-label">是否公开：</label>
            <div class="col-sm-8">
                <input type="radio" id="public-yes" name="is-public" value="yes">
                <label for="public-yes" style="margin-right: 10px;">是</label>
                <input type="radio" id="public-no" name="is-public" value="no" checked>
                <label for="public-no">否</label>
            </div>
        </div>

        <!-- 加载覆盖层 -->
        <div id="loading-overlay" style="display: none;">
            <div class="spinner"></div>
            <p>请耐心等待...</p>
            <div class="progress-container">
                <div class="progress-bar" id="progress-bar">0%</div>
            </div>
        </div>
    </form>


</div>
<div th:include="include::footer"></div>
<script type="text/javascript">
    var prefix = ctx + "detection/detectionDataset"
    var formData = new FormData();
    $("#form-detectionDataset-add").validate({
        rules: {
            xxxx: {
                required: true,
            },
        },
        focusCleanup: true
    });

    // 验证文件类型
    function validateFileType(files, validTypes) {
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            var fileType = file.type;
            var fileExtension = file.name.split('.').pop().toLowerCase();

            // 检查文件类型和扩展名是否符合要求
            if (!validTypes.includes(fileType) && !validTypes.includes(fileExtension)) {
                return false;
            }
        }
        return true;
    }

    function submitHandler() {
        // 使用正则表达式检查是否为数字
        var numberRegex = /^\d+$/;
        var heightValue = document.getElementById('height').value;
        var widthValue = document.getElementById('width').value;
        var imageUpload = document.getElementById('image-upload').files;
        var labelUpload = document.getElementById('label-upload').files;

        var validImageTypes = ['image/jpeg', 'image/png', 'image/tiff', 'jpg', 'jpeg', 'png', 'tif', 'tiff'];
        var validLabelTypes = ['txt'];

        // 校验上传的图片类型
        if (!validateFileType(imageUpload, validImageTypes)) {
            Swal.fire({
                icon: 'error',
                title: '错误',
                text: '请上传符合要求的图片类型 (jpg, jpeg, png, tif, tiff)',
                showConfirmButton: true,
                allowOutsideClick: false,
                allowEscapeKey: false
            });
            return;  // 阻止表单提交
        }

        // 校验上传的标签类型
        if (!validateFileType(labelUpload, validLabelTypes)) {
            Swal.fire({
                icon: 'error',
                title: '错误',
                text: '请上传符合要求的标签类型 (txt)',
                showConfirmButton: true,
                allowOutsideClick: false,
                allowEscapeKey: false
            });
            return;  // 阻止表单提交
        }

        var datasetName = document.getElementById('name').value;
        // axios发送get请求判断名称是否重复
        axios.get(prefix + "/checkName?name=" + datasetName)
            .then(function (response) {
                if (response.data === true) {
                    Swal.fire({
                        icon: 'error',
                        title: '错误',
                        text: '数据集名称已存在',
                        showConfirmButton: true,
                        allowOutsideClick: false,
                        allowEscapeKey: false
                    });
                    return;  // 阻止表单提交
                } else {
                    console.log("开始上传文件")
                    if ($.validate.form()
                        && document.getElementById('name').value != '' && document.getElementById('height').value != '' && document.getElementById('width').value != ''
                        && document.getElementById('image-count').textContent.split('：')[1] != '0'
                        && numberRegex.test(heightValue)
                        && numberRegex.test(widthValue)) {
                        var nameValue = document.getElementById('name').value;
                        formData.append('datasetName', nameValue);
                        // console.log( document.getElementById('height').value)
                        formData.append('height', document.getElementById('height').value);
                        formData.append('width', document.getElementById('width').value);
                        // console.log("height:"+document.getElementById('height').value);
                        // console.log("width:"+document.getElementById('width').value);
                        // 获取是否公开的选项
                        var isPublicValue = $("input[name='is-public']:checked").val();
                        // 如果是公开的，则将 isPublicValue 置为 1，否则置为 0
                        if (isPublicValue == 'yes') {
                            isPublicValue = 1;
                        } else {
                            isPublicValue = 0;
                        }
                        formData.append('isPublic', isPublicValue);
                        // 显示加载层（可选）
                        // 显示加载覆盖层和进度条
                        var overlay = document.getElementById('loading-overlay');
                        var progressBar = document.getElementById('progress-bar');
                        overlay.style.display = 'flex';
                        progressBar.style.width = '0%';
                        progressBar.textContent = '0%';
                        console.log("开始发送请求")
                        axios.post('/detection/detectionDataset/uploadDataset', formData, {
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            },
                            // 上传进度事件
                            onUploadProgress: function (event) {
                                if (event.lengthComputable) {
                                    var percentComplete = Math.round((event.loaded / event.total) * 100);
                                    progressBar.style.width = percentComplete + '%';
                                    progressBar.textContent = percentComplete + '%';
                                }
                            }
                        })
                            .then(function (response) {
                                if (response.status === 200 && response.data !== "图片和标签文件格式不匹配") {
                                    Swal.fire({
                                        icon: 'success',
                                        title: '文件上传成功',
                                        showConfirmButton: false,
                                        timer: 1000
                                    }).then(function () {
                                        $('#form-app01Dataset-add').serialize();
                                        $.modal.close();
                                    });
                                } else {
                                    Swal.fire({
                                        icon: 'error',
                                        title: '错误',
                                        text: response.data,
                                        showConfirmButton: true,
                                        timer: 5000
                                    });
                                }
                                overlay.style.display = 'none'; // 隐藏加载覆盖层
                            })
                            .catch(function (error) {
                                Swal.fire({
                                    icon: 'error',
                                    title: '上传出错，请重试',
                                    showConfirmButton: false,
                                    timer: 2000
                                });
                                overlay.style.display = 'none'; // 隐藏加载覆盖层
                            });
                    }
                    else {
                        // 验证失败的处理
                        if (document.getElementById('name').value == '' || document.getElementById('height').value == '' || document.getElementById('width').value == '') {
                            $.modal.alert('表格信息未填写完整！');
                        }
                        else if (document.getElementById('image-count').textContent.split('：')[1] == '0')
                        {
                            $.modal.alert('请上传图片！');
                        } else {
                            $.modal.alert('图片尺寸请输入数字！');
                        }
                    }
                }
            })
            .catch(function (error) {
                Swal.fire({
                    icon: 'error',
                    title: '请求失败',
                    text: error+'检查任务名称失败，请稍后重试',
                    showConfirmButton: true,
                    allowOutsideClick: false,
                    allowEscapeKey: false
                });
            });

        window.parent.postMessage('refreshTable', '*');
    }


    $(document).ready(function () {
        // 上传图片
        $('#image-upload').on('change', function () {
            formData.delete('image-upload'); // 清空之前的图片文件
            var files = $(this)[0].files; // 获取文件列表
            var fileCount = files.length; // 获取文件数量

            if (files.length > 0) {
                for (var i = 0; i < files.length; i++) {
                    formData.append('image-upload', files[i]);
                }
            }
            var imageCountSpan = document.getElementById('image-count');
            imageCountSpan.textContent = '上传的训练图片数量：' + fileCount;
        });

        // 上传标签
        $('#label-upload').on('change', function () {
            formData.delete('label-upload'); // 清空之前的图片文件
            var files = $(this)[0].files; // 获取文件列表
            var fileCount = files.length; // 获取文件数量

            if (files.length > 0) {
                for (var i = 0; i < files.length; i++) {
                    formData.append('label-upload', files[i]);
                    console.log("文件名:", files[i].name)
                }
            }
            var imageCountSpan = document.getElementById('label-count');
            imageCountSpan.textContent = '上传的训练标签数量：' + fileCount;
        });
        //  刷新父页面
        window.parent.postMessage('refreshTable', '*');
    });


</script>
</body>
</html>
